use binance_sdk::ws::market_types::MarketStreamEvent;
use std::sync::Arc;
use tokio::sync::broadcast;
use crate::app_config::AppConfig;

#[derive(Clone)]
pub struct BroadcastHandler {
    config: AppConfig,
    sender: Arc<broadcast::Sender<MarketStreamEvent>>,
}

impl BroadcastHandler {
    pub fn new(config: AppConfig) -> Self {
        let (sender, _) = broadcast::channel(1024);
        Self {
            config,
            sender: Arc::new(sender),
        }
    }

    pub fn spawn_consumer(&self)
    {
        let mut rx = self.sender.subscribe();
        tokio::spawn(async move {
            while let Ok(event) = rx.recv().await {
                println!("{:?}", event);
                match event {
                    MarketStreamEvent::OrderBook(order_book) => {
                        // todo serialize via proto buffer, then zmq pub.
                        // send multipart topic "binance.usd_m.[symbol].lc" payload: orderbook

                    }
                    _ => {}
                }
            }
        });
    }

    pub fn send(&self, event: MarketStreamEvent) {
        let _ = self.sender.send(event);
    }
}
